package util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DButil {
	private static final String A = "jdbc:mysql://localhost:3306/web";
	private static final String B = "root";
	private static final String C = "123456";
	public static Connection connect = null;
	public static PreparedStatement pstmt = null;
	public static ResultSet rs = null;

	public static void closeAll(ResultSet rs, Connection connect, Statement pstmt) {
		try {
			if (rs != null)
				rs.close();
			if (pstmt != null)
				pstmt.close();
			if (connect != null)
				connect.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

//增删改
	public static boolean executeUpdate(String sql, Object[] params) {

		try {
			Class.forName("com.mysql.jdbc.Driver");
			connect = DriverManager.getConnection(A, B, C);
			// String sql = "UPDATE t_student SET address = ?, name = ?, sage = ? WHERE no =
			// ?";
			pstmt = connect.prepareStatement(sql);
			for (int i = 0; i < params.length; i++) {
				pstmt.setObject(i + 1, params[i]);
			}
			int count = pstmt.executeUpdate();
			if (count > 0) {
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			closeAll(null, connect, pstmt);
		}
	}

//通用的查
	public static ResultSet executeRs(String sql, Object[] params) {// 根据sql语句查询也可能有？ 需要params
		try {
			Class.forName("com.mysql.jdbc.Driver");
			connect = DriverManager.getConnection(A, B, C);
			// String sql = "select * from t_student ";
			pstmt = connect.prepareStatement(sql);
			if (params != null) {
				for (int i = 0; i < params.length; i++) {
					pstmt.setObject(i + 1, params[i]);
				}
			}

			rs = pstmt.executeQuery();
			return rs;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	public static void main(String[] args) {
		String sql="select count(*) from user where username=? and password=?";
		
		ResultSet rs2 = executeRs(sql,  new Object[]{"1","1"});
		if(rs2!=null)
			System.out.println(123);
	}
}
